package com.watermoniter.util;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.watermoniter.BuildConfig;
import com.watermoniter.view.BaseActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 作者：minj on 2017/9/27 09:55
 * 网络请求的底层封装
 */
public class BasicHttp {

    public interface IMyCallBack{
        public void onResponse(String resonseData);
        public void onFailure(String resonseData);
    }


    private static OkHttpClient mOkHttpClient;

    private BasicHttp() {
    }

    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        if(BuildConfig.DEBUG){
            builder.addInterceptor(new LoggingInterceptor());
        }
        mOkHttpClient=builder.build();
    }

    public static BasicHttp getInstance(Context context) {
        return null;
    }


    public static boolean postExec(Context context, String url, RequestBody postData, IMyCallBack myCallBack) {
       return postExec(context,url,postData, myCallBack,true);
    }

    /***
     *
     * @param context
     * @param url
     * @param postData
     * @param myCallBack
     * @param isShowToast
     * @return true表示已经发出请求 false表示有可能由于网络问题 请求没有发出去
     */
    public static boolean postExec(final Context context, String url, RequestBody postData, final IMyCallBack myCallBack, final boolean isShowToast) {

        if (!AppConfig.isNetworkAvailable(context)) {
            if (context instanceof BaseActivity && isShowToast) {
                ((BaseActivity) context).showToast("网络不给力，请稍后再试");
            }
            return false;
        }

        if (context instanceof BaseActivity && isShowToast) {
            ((BaseActivity) context).showLoadingDialog();
        }



        Request request = new Request.Builder().url(url).post(postData).build();

        //new call
        Call call = mOkHttpClient.newCall(request);

        //请求加入调度
        common_exec(context,call,myCallBack,isShowToast);
        return true;
    }

    private static void common_exec(final Context context, Call call, final IMyCallBack myCallBack, final boolean isShowToast){
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call,final IOException e) {

                if (context instanceof BaseActivity && isShowToast) {
                    ((BaseActivity) context).dismissLoadingDialog();
                }

                if(myCallBack==null){
                    return;
                }

                if (context instanceof BaseActivity ) {
                    ((BaseActivity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myCallBack.onFailure(e.getMessage());
                        }
                    });
                }else{
                    myCallBack.onFailure(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call,final Response response) throws IOException {

                if (context instanceof BaseActivity && isShowToast) {
                    ((BaseActivity) context).dismissLoadingDialog();
                }

                final String responseData=response.body().string();

                JSONObject jsonObject=null ;

                try {
                    jsonObject= JSONObject.parseObject(responseData);
                }catch (Exception ex){
                    ((BaseActivity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                        if(isShowToast){
                            ((BaseActivity) context).showToast("服务错误");
                        }
                        }
                    });
                    return;
                }

                if (jsonObject.getIntValue("StatusCode") == 200) {
                    if(myCallBack==null){
                        return;
                    }
                    if (context instanceof BaseActivity ) {
                        ((BaseActivity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                myCallBack.onResponse(responseData);
                            }
                        });
                    }else{
                        myCallBack.onResponse(responseData);
                    }
                } else {
                    if (context instanceof BaseActivity ) {
                        final String msg=jsonObject.getString("Msg");
                        ((BaseActivity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(isShowToast){
                                    ((BaseActivity) context).showToast(msg);
                                }
                                if(myCallBack==null){
                                    return;
                                }
                                myCallBack.onFailure(responseData);
                            }
                        });
                    }else{
                        if(myCallBack==null){
                            return;
                        }
                        myCallBack.onFailure(responseData);
                    }
                }
            }
        });
    }

    public static boolean getExec(final Context context, String url, final IMyCallBack myCallBack, final boolean isShowToast) {

        if (!AppConfig.isNetworkAvailable(context)) {
            if (context instanceof BaseActivity && isShowToast) {
                ((BaseActivity) context).showToast("网络不给力，请稍后再试");
            }
            return false;
        }

        if (context instanceof BaseActivity && isShowToast) {
            ((BaseActivity) context).showLoadingDialog();
        }

        Request request = new Request.Builder().url(url).build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        common_exec(context,call,myCallBack,isShowToast);
        return true;
    }



    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //这个chain里面包含了request和response，所以你要什么都可以从这里拿
            Request request = chain.request();



            long t1 = System.nanoTime();//请求发起的时间

            if(request.method().equals("POST")){
                LogX.snipet("-------HTTP_REQUEST-------", String.format("发送请求 %s on %s%n%s--%s",request.url(), chain.connection(), request.headers(),((FormBody)request.body()).value(1)));
            }else{
                LogX.snipet("-------HTTP_REQUEST-------", String.format("发送请求 %s on %s%n%s",request.url().toString().replaceAll("%22","'"), chain.connection(), request.headers()));
            }



            Response response = chain.proceed(request);

            long t2 = System.nanoTime();//收到响应的时间

            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);

            LogX.snipet("******HTTP_RESPONSE******", String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n",
                    response.request().url(),
                    responseBody.string(),
                    (t2 - t1) / 1e6d));

            return response;
        }
    }






}
